import { constantRoutes, asyncRouters } from "@/router/routeMap";

// 通过route.meta.roles判断是否与当前roles匹配
const hasPermission = (roles, route) => {
    if (route.meta && route.meta.roles) {
        return roles.some((role) => route.meta.roles.includes(role));
    } else {
        return true;
    }
};

// 递归遍历路由，把有权限的路由遍历出来
const filterAsyncRoutes = (routes, roles) => {
    const res = [];
    routes.forEach((route) => {
        const tmp = { ...route };
        if (hasPermission(roles, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, roles);
            }
            res.push(tmp);
        }
    });
    return res;
};
const initState = {
    routes: [],
    addRoutes: [],
};
const permission = {
    state: {
        routes: [],
        addRoutes: [],
    },
    mutations: {
        PERMISSION_RESET_STATE: (state) => {
            for (let key in initState) {
                state[key] = initState[key];
            }
        },
        SET_ROUTES: (state, routes) => {
            state.addRoutes = routes;
            state.routes = constantRoutes.concat(routes);
        },
    },
    actions: {
        generateRoutes({ commit }, roles) {
            return new Promise((resolve) => {
                const accessedRoutes = filterAsyncRoutes(asyncRouters, roles); // 过滤出有权限的路由
                // console.log(accessedRoutes, "过滤出的路由--------------");
                commit("SET_ROUTES", accessedRoutes); // 把有权限的路由塞到vuex中
                resolve(accessedRoutes);
            });
        },
    },
};

export default permission;
